<template>
  <div>
    <el-dialog v-model="dialogVisible" width="30%" title="Login" align-center>
      <el-form label-position="top">
        <el-form-item label="账号">
          <el-input v-model="username"></el-input>
        </el-form-item>

        <el-form-item label="密码">
          <el-input show-password v-model="password"></el-input>
        </el-form-item>

        <el-button style="width: 100%;margin-top: 20px" @click="login">登录</el-button>
      </el-form>


    </el-dialog>

    <el-col class="m-user-box">
      <el-link :underline="false" @click="openDialog">
        <el-avatar :src="picSrc"></el-avatar>
        <span style="padding-left: 8px">{{ nickname }}</span>
      </el-link>

      <el-tooltip content="切换角色">
        <el-link style="padding-left: 10px;padding-top: 2px" :underline="false" @click="switchUser">
          <el-icon :size="20">
            <Switch/>
          </el-icon>
        </el-link>
      </el-tooltip>

      <el-tooltip content="退出登录">
        <el-link style="padding-left: 10px;padding-top: 2px" :underline="false" @click="logOut">
          <el-icon :size="20">
            <SwitchButton/>
          </el-icon>
        </el-link>
      </el-tooltip>

      <el-link style="padding-left: 10px;padding-top: 2px" :underline="false" v-show="this_name_show">
        当前角色({{ this_name }})
      </el-link>

    </el-col>

    <el-col>

      <el-col class="m-box">
        <el-card style="height: 100%;overflow-y: scroll">
          <template #header>
            <span>我的奇遇</span>
          </template>
          <el-table :data="meetData" border>
            <el-table-column prop="server" label="区服"></el-table-column>
            <el-table-column prop="name" label="角色名"></el-table-column>
            <el-table-column prop="serendipity" label="奇遇"></el-table-column>
            <el-table-column label="触发时间">
              <template #default="scope">
                <span>{{ getDate(scope.row.time) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="奇遇分析">
              <template #default>
                <el-button link type="primary">触发时段</el-button>
                <el-button link type="primary">触发间隔</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </el-col>


      <el-row :gutter="10" style="margin-top: 10px">
        <el-col :span="12" class="m-box">
          <el-card style="height: 100%;overflow-y: scroll">
            <template #header>
              官方公告
            </template>
            <template v-for="n in noticeList" :key="n.id">
              <el-col>
                <el-button link @click="openUrl(n.url)">{{ n.title }}</el-button>
              </el-col>
              <el-divider/>
              <!--                <el-link @click="openUrl(n.url)">{{ n.url }}&nbsp; &lang;&lang;==============点我</el-link>-->
            </template>
          </el-card>
        </el-col>
        <el-col :span="12" class="m-box">
          <el-card>
            没想好写啥
          </el-card>

        </el-col>
      </el-row>

    </el-col>

    <el-drawer v-model="bindVisible" title="添加角色" size="600px">
      <el-row :gutter="20">
        <el-col :span="6">

          <el-image :src="bgSrc"></el-image>

          <el-col style="text-align: center;position: relative;bottom: 60px">
            <el-image :src="logoSrc" :fit="'fill'"></el-image>
            <el-image class="m-logo-status" :src="logoStatus"></el-image>
          </el-col>

        </el-col>

        <el-col class="m-job-b" :span="18">
          <el-form label-position="top" :rules="rules" :model="sub" ref="ruleFormRef">
            <el-form-item label="角色名" prop="username">
              <el-input v-model="sub.username"></el-input>
            </el-form-item>

            <el-form-item label="区服" prop="server">
              <el-cascader placeholder="选择区服" :options="server_name" v-model="sub.server"
                           style="width: 100%;"></el-cascader>
            </el-form-item>

            <el-form-item label="职业" prop="job">
              <!--          <el-cascader placeholder="绑定区服" :options="server_name" v-model="sub.server"></el-cascader>-->
              <el-select v-model="sub.job" placeholder="绑定区服" style="width: 100%;" @change="changePic">
                <el-option v-for="item in job_list" :key="item.name" :label="item.name" :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button style="width: 100%;margin-top: 40px" @click="addUser(ruleFormRef)">确认添加</el-button>
              <!--              <el-button style="width: 100%">重置</el-button>-->
            </el-form-item>


          </el-form>
        </el-col>
      </el-row>


    </el-drawer>

    <el-drawer title="切换角色" v-model="selfVisible" size="600">
      <el-button @click="bindVisible = true">添加角色</el-button>
      <el-table :data="userData" stripe>
        <el-table-column prop="userver"></el-table-column>
        <el-table-column prop="userver2"></el-table-column>
        <el-table-column prop="uname"></el-table-column>
        <el-table-column prop="ujob"></el-table-column>
        <el-table-column>
          <template #default="scope">
            <el-button link v-if="scope.row.udefault === 0" @click="cutUser(scope.row.uid,scope.row.bid)">切换角色
            </el-button>
            <el-button link disabled v-if="scope.row.udefault === 1">当前角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref} from 'vue';
import {userHttp} from "@/axios/userHttp";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {jobList, SERVER_NAME3} from "@/constant/constant";
import {j3api} from "@/axios/j3http";

export default defineComponent({
  name: 'MainPage',
  data() {
    return {
      username: '',
      password: '',
      picSrc: 'https://img0.baidu.com/it/u=3419349721,319645530&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1688230800&t=43b17e4ccbe7c2232de22dcc0fc73c9d',
      dialogVisible: false,
      nickname: '未登录',
      bindVisible: false,
      selfVisible: false,
      server_name: SERVER_NAME3,
      job_list: jobList,
      bgSrc: 'https://jx3.xoyo.com/gn/assets/images/page3/school-role/s_daozong.a4f25a9c.png',
      logoSrc: 'https://jx3.xoyo.com/gn/assets/images/page3/school-logo/daozong.ab9149bc.png',
      logoStatus: 'https://jx3.xoyo.com/gn/assets/images/page3/school.2ba811ec.png',
      sub: {
        username: '',
        server: [],
        job: '刀宗'
      },
      ruleFormRef: ref(null),
      rules: {
        username: [
          {
            required: true, message: '请输入角色名', trigger: 'blur'
          },
          {min: 2, max: 8, message: '长度为2到8位', trigger: 'blur'}
        ],
        server: [
          {
            required: true,
            message: '请选择区服',
            trigger: 'change',
          }
        ],
        job: [
          {
            required: true,
            message: '请选择职业',
            trigger: 'change',
          }
        ]
      },
      meetData: [],
      userData: [],
      noticeList: [],
      this_name: '',
      this_name_show: false
    }
  },
  methods: {
    openUrl(url: string) {
      const win = window as any
      win.shell.openUrl(url)
    },
    cutUser(uid: string, bid: string) {
      userHttp.updateDefaultUser(uid, bid).then((res: any) => {
        if (res.code === 200) {
          ElNotification.success({message: '切换成功'})
          this.selfVisible = false
          location.reload()
        } else {
          ElNotification.error({message: '切换失败'})
        }
      })

    },
    async addUser() {
      if (this.sub.username === '') {
        ElMessage.error({message: '角色名不能为空'})
        return
      }

      if (this.sub.server.length === 0) {
        ElMessage.error({message: '请选择大区'})
        return
      }

      userHttp.addBindUser(this.sub.username, this.sub.server, this.sub.job).then((res: any) => {
        console.log(res);
        if (res.code === 200) {
          ElNotification.success({message: '添加成功'})
        } else {
          ElNotification.error({message: res.msg})
        }
      })

    },
    changePic(val: string) {
      /* eslint-disable */
      // console.log(val);
      for (let job of jobList) {
        if (job.name === val) {
          this.bgSrc = job.url
          this.logoSrc = job.logo
          // this.bindVisible = true
          break
        }
      }
      /* eslint-disable */
    },
    switchUser() {
      if (sessionStorage.getItem('login_status') !== '1') {
        ElMessage.info({message: '您还未登录,请先登录'})
        return
      }

      this.selfVisible = true


    },
    openDialog() {
      if (sessionStorage.getItem('login_status') === '1') {
        this.bindUser()
      } else {
        this.dialogVisible = true
      }
    },
    logOut() {
      sessionStorage.removeItem('login_status')
      localStorage.removeItem('user_info')
      localStorage.removeItem('token')
      this.nickname = "未登录"
      this.this_name_show = false
      this.meetData = []
    },
    async login() {
      await userHttp.login(this.username, this.password).then((res: any) => {
        if (res.code !== 200) {
          ElMessage.error(res.msg)
          return
        }

        if (res.code === 200) {
          ElMessage.success("登录成功,即将跳转...")
          localStorage.setItem("user_info", JSON.stringify(res.user))
          localStorage.setItem("token", res.token)
          sessionStorage.setItem('login_status', '1')
          setTimeout(() => {
            this.dialogVisible = false
          }, 2000)

          this.nickname = res.user.nickname
          this.bindUser()
        }

      })
    },
    bindUser() {
      userHttp.getBindUser().then((res: any) => {
        if (res.code === 200) {
          console.log(res);
          if (res.data.length === 0) {
            ElMessageBox.confirm('您还未绑定角色,是否绑定', '提示', {
              confirmButtonText: '绑定',
              cancelButtonText: '取消',
              type: 'success',
            }).then(() => {
              this.bindVisible = true
            })
            return
          } else {
            this.userData = res.data
            this.getUserMessage(res.data)
          }

        } else {
          ElMessage.error(res.msg)
        }
      })
    },
    getUserMessage(data: any) {
      for (let datum of data) {
        if (datum.udefault === 1) {
          j3api.searchMeet(datum.userver, datum.userver2, datum.uname).then((res: any) => {
            console.log(res)
            this.meetData = res.result
            this.this_name = datum.uname
            this.this_name_show = true
          })
          return
        }
      }
    },
    getDate(timestamp: string) {
      // 此处时间戳以毫秒为单位
      let date = new Date(parseInt(timestamp) * 1000);
      let Year = date.getFullYear();
      let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
      let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
      let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
      let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
      let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());

      return Year + '-' + Moth + '-' + Day + '   ' + Hour + ':' + Minute + ':' + Sechond;
    }
  },

  mounted() {
    if (sessionStorage.getItem("login_status") === '1') {
      const userInfo = JSON.parse(localStorage.getItem("user_info") + "")
      this.nickname = userInfo.nickname
      this.bindUser()
    }

    j3api.getNotice().then((res: any) => {
      this.noticeList = res.data
    })
  }
});
</script>
